package cn.com.cetccst.appshield.ui.model;

import android.content.Context;

import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.com.cetccst.appshield.R;
import cn.com.cetccst.appstore.database.AppStoreRepository;
import cn.com.cetccst.appstore.database.model.AppModel;
import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.BWAppEntity;
import cn.com.cetccst.datacenter.policy.fence.GFence;
import cn.com.cetccst.datacenter.policy.type.BlackWhiteAppSetting;
import cn.com.cetccst.tools.pm.AppPackage;

public class AppShieldViewModel extends ViewModel {

    private final Map<String, Observer<AppModel>> observers = new HashMap<>();
    public final MutableLiveData<Boolean> enable = new MutableLiveData<>(false);
    public final MutableLiveData<Boolean> white = new MutableLiveData<>(false);
    public final MutableLiveData<GFence> geoFence = new MutableLiveData<>();
    public final MutableLiveData<List<BlackWhiteAppSetting.ValidTime>> validTimeFences = new MutableLiveData<>();
    public final LiveData<List<BWAppEntity>> appList = PolicyRepository.getInstance().getAllBWAppEntity();

    public void setAppConfig(Context context, LifecycleOwner viewLifecycleOwner, BlackWhiteAppSetting blackWhiteAppSetting, Callback callback) {
        enable.setValue(blackWhiteAppSetting.isEnable());
        white.setValue(blackWhiteAppSetting.isBlackWhiteType());
        geoFence.setValue(blackWhiteAppSetting.getValidLocation());
        validTimeFences.setValue(blackWhiteAppSetting.getValidTime());
        List<BWAppEntity> apps = new ArrayList<>();
        unregisterObservers();
        for (BlackWhiteAppSetting.App app : blackWhiteAppSetting.getApps()) {
            BWAppEntity entity = generateBWAppEntity(context, viewLifecycleOwner, app, callback);
            entity.setWhite(blackWhiteAppSetting.isBlackWhiteType());
            apps.add(entity);
        }

//        List<BlackWhiteAppSetting.App> forbiddenApps = blackWhiteAppSetting.getForbiddenApps();
        //TODO 白中带黑的场景，这一期不做
        PolicyRepository.getInstance().saveAllBWApps(apps);
    }

    private void unregisterObservers() {
        for (String appId : observers.keySet()) {
            AppStoreRepository.getInstance().loadAppByAppId(appId).removeObserver(Objects.requireNonNull(observers.get(appId)));
        }
        observers.clear();
    }

    private BWAppEntity generateBWAppEntity(Context context, LifecycleOwner viewLifecycleOwner, BlackWhiteAppSetting.App app, Callback callback) {
        BWAppEntity entity = new BWAppEntity();
        entity.setName(app.getAppName());
        entity.setPackageName(app.getPackageName());
        entity.setVersionName(app.getPackageName());
        entity.setDescription(context.getString(R.string.app_source_none));
        entity.setAppSource(BWAppEntity.SOURCE_NONE);
        AppModel appModel = AppStoreRepository.getInstance().getAppByPackageName(app.getPackageName());
        if (appModel != null) {
            entity.setAppSource(BWAppEntity.SOURCE_STORE);
//            appModel.detectAppStatus(context);
            initEnitiyFromAppModel(entity, appModel);
            Observer<AppModel> observer = model -> {
                initEnitiyFromAppModel(entity, model);
                callback.onItemChanged(entity);
            };
            observers.put(appModel.getAppId(), observer);
            AppStoreRepository.getInstance().loadAppByAppId(appModel.getAppId()).observe(viewLifecycleOwner, observer);
            return entity;
        }

        boolean isInstalledApp = AppPackage.isPackageFound(context, app.getPackageName());
        if (isInstalledApp) {
            entity.setSize(AppPackage.getPackageSize(context, app.getPackageName()));
            entity.setVersionName(AppPackage.getVersionName(context, app.getPackageName()));
            boolean isSystemApp = AppPackage.isSystemPackage(context, app.getPackageName());
            if (isSystemApp) {
                entity.setAppSource(BWAppEntity.SOURCE_SYSTEM);
                entity.setDescription(context.getString(R.string.app_source_system));
            } else {
                entity.setAppSource(BWAppEntity.SOURCE_USER);
                entity.setDescription(context.getString(R.string.app_source_user));
            }
        }
        return entity;
    }

    private static void initEnitiyFromAppModel(BWAppEntity entity, AppModel appModel) {

        entity.setAppModelId(appModel.getAppId());
        entity.setAppModelHash(Objects.hash(appModel.getAppId(), appModel.getRange(), appModel.getStatus(), appModel.isNeedUpgrade()));
        entity.setImgUrl(appModel.getAppBigIconUrl());
        entity.setDescription(appModel.getCategoryName());
        entity.setSize(appModel.getAppSummary().getAppSize());
        entity.setVersionName(appModel.getAppSummary().getAppVersion());
    }

    public int getTipRes(boolean isWhite) {
        if (isWhite)
            return R.string.white_list_tip;
        else
            return R.string.black_list_tip;
    }

    public interface Callback {
        void onItemChanged(BWAppEntity entity);
    }
}
